package driver.android;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.core.content.res.ResourcesCompat;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import driver.android.http.CommonOkHttpClient;
import driver.util.Constants;
import driver.util.IHttpCallBack;
import driver.util.Util;
import okhttp3.Response;

public class FlashDriverUpdatePasswordActivity extends Activity implements View.OnClickListener, IHttpCallBack {

    private FlashDriverTaskHandler mHandler;
    private ProgressDialog mProgressDialog;
    private SharedPreferences mFlashSharedPreferences;
    private String mFlashSharePreferenceName = "Flash";
    private EditText mOldPassword;
    private EditText mNewPassword;
    private EditText mConfirmPassword;
    private ImageView mShowOldPasswordImage;
    private ImageView mShowNewPasswordImage;
    private ImageView mShowConfirmPasswordImage;
    private ImageView mClearOldPassword;
    private ImageView mClearNewPassword;
    private ImageView mClearConfirmPassword;
    private Button mUpdatePassword;
    private Button mBackPackageListActivity;
    private String mLoginToken;
    private String mUuid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.f_user_update_password_activity);
        initActivity();
    }

    private void initActivity() {
        mProgressDialog = new ProgressDialog(this);
        mHandler = new FlashDriverTaskHandler(this);
        mFlashSharedPreferences = getSharedPreferences(mFlashSharePreferenceName, Context.MODE_PRIVATE);
        mOldPassword = (EditText) this.findViewById(R.id.login_user_old_pwd_edit);
        mNewPassword = (EditText) this.findViewById(R.id.login_user_new_pwd_edit);
        mConfirmPassword = (EditText) this.findViewById(R.id.login_user_confirm_pwd_edit);
        mShowOldPasswordImage = (ImageView) this.findViewById(R.id.user_old_pwd_show);
        mShowOldPasswordImage.setOnClickListener(this);
        mShowOldPasswordImage.setTag(R.id.password_show, false);
        mShowNewPasswordImage = (ImageView) this.findViewById(R.id.user_new_pwd_show);
        mShowNewPasswordImage.setOnClickListener(this);
        mShowNewPasswordImage.setTag(R.id.password_show, false);
        mShowConfirmPasswordImage = (ImageView) this.findViewById(R.id.user_confirm_pwd_show);
        mShowConfirmPasswordImage.setOnClickListener(this);
        mShowConfirmPasswordImage.setTag(R.id.password_show, false);
        mClearOldPassword = (ImageView) this.findViewById(R.id.user_old_pwd_clear);
        mClearOldPassword.setOnClickListener(this);
        mClearNewPassword = (ImageView) this.findViewById(R.id.user_new_pwd_clear);
        mClearNewPassword.setOnClickListener(this);
        mClearConfirmPassword = (ImageView) this.findViewById(R.id.user_confirm_pwd_clear);
        mClearConfirmPassword.setOnClickListener(this);
        mUpdatePassword = (Button) this.findViewById(R.id.update_password_button);
        mUpdatePassword.setOnClickListener(this);
        mBackPackageListActivity = (Button) this.findViewById(R.id.back_package_list_button);
        mBackPackageListActivity.setOnClickListener(this);
        mLoginToken = mFlashSharedPreferences.getString("token", "");
        mUuid = mFlashSharedPreferences.getString("uuid", "");
    }

    private void showToast(String title) {
        Toast.makeText(this, title, Toast.LENGTH_LONG).show();
    }


    private void showProgressDialog(String title) {
        if (mProgressDialog != null) {
            mProgressDialog.setMessage(title);
            mProgressDialog.setCanceledOnTouchOutside(false);
            if (!this.isFinishing()) {
                mProgressDialog.show();
            }
        }
    }

    private void closeProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void parseJsonBundle(Bundle bundle) {
        String taskJsonDetail = bundle.getString("taskBody");
        String result = Util.getJsonKeyValue("result", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("result", taskJsonDetail).toString();
        if (result != null && result.equals("true")) {
            SharedPreferences.Editor editor = mFlashSharedPreferences.edit();
            editor.putString("token", "");
            editor.putString("uuid", "");
            Intent intent = new Intent();
            intent.setClass(this, FlashDriverLoginActivity.class);
            this.startActivity(intent);
            this.finish();
        } else {
            showToast("Please try again later...");
        }
    }

    private void controlEditTextStyle(Drawable drawableClose, Drawable drawableOpen, EditText editText, ImageView imageview) {
        boolean showPassword = (boolean) imageview.getTag(R.id.password_show);
        if (showPassword) {
            imageview.setBackground(drawableClose);
            imageview.setTag(R.id.password_show, false);
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {
            imageview.setBackground(drawableOpen);
            imageview.setTag(R.id.password_show, true);
            editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }

    private void updatePassword() {
        String oldPassword = mOldPassword.getText().toString().trim();
        String newPassword = mNewPassword.getText().toString().trim();
        String confirmPassword = mConfirmPassword.getText().toString().trim();
        if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
            showToast("Please check your input");
            return;
        }
        if (!newPassword.equals(confirmPassword)) {
            showToast("New Password not same with Confirm Password");
            return;
        }
        this.showProgressDialog("Please wait...");
        CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
        Map<String, String> headersParams = new HashMap<>();
        headersParams.put("token", mLoginToken);
        String url = Constants.ROOT + mUuid + Constants.UPDATE_PASSWORD;
        Map<String, String> params = new HashMap<>();
        params.put("password", oldPassword);
        params.put("new_password", newPassword);
        params.put("new_password2", confirmPassword);
        Util.debugApp('d', "更新密码的URL  " + url);
        okHttpInstance.doPost(url, headersParams, params);
    }

    private void showTaskListActivity() {
        Intent intent = new Intent();
        intent.setClass(this, FlashDriverPackageListActivity.class);
        this.startActivity(intent);
        this.finish();
    }

    private static class FlashDriverTaskHandler extends Handler {

        private final WeakReference<FlashDriverUpdatePasswordActivity> mActivity;

        private FlashDriverTaskHandler(FlashDriverUpdatePasswordActivity ac) {
            this.mActivity = new WeakReference<FlashDriverUpdatePasswordActivity>(ac);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FlashDriverUpdatePasswordActivity activity = mActivity.get();
            if (activity != null) {
                activity.closeProgressDialog();
                switch (msg.what) {
                    case Constants.UPDATE_PASSWORD_SUCCESS_MESSAGE:
                        Bundle bundle = msg.getData();
                        activity.parseJsonBundle(bundle);
                        break;
                    case Constants.UPDATE_PASSWORD_FAIL_MESSAGE:
                        activity.showToast("Network Error...");
                        break;
                    case Constants.UN_KNOW_RESPONSE_CODE:
                        Bundle bundleUnKnowCode = msg.getData();
                        String unKnowBody = bundleUnKnowCode.getString("codeInvalid");
                        String description = Util.getJsonKeyValue("description", unKnowBody);
                        if (description == null) {
                            activity.showToast("Network Error");
                        } else {
                            activity.showToast(description);
                        }
                        break;
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        boolean connect = Util.isNetworkAvailable(this);
        if (!connect) {
            showToast("Please check your network state");
            return;
        }
        Drawable drawableOpen = ResourcesCompat.getDrawable(getResources(), R.drawable.eye_open, null);
        Drawable drawableClose = ResourcesCompat.getDrawable(getResources(), R.drawable.eye_close, null);
        int id = v.getId();
        switch (id) {
            case R.id.user_old_pwd_show:
                controlEditTextStyle(drawableClose, drawableOpen, mOldPassword, mShowOldPasswordImage);
                break;
            case R.id.user_old_pwd_clear:
                mOldPassword.setText("");
                break;
            case R.id.user_new_pwd_show:
                controlEditTextStyle(drawableClose, drawableOpen, mNewPassword, mShowNewPasswordImage);
                break;
            case R.id.user_new_pwd_clear:
                mNewPassword.setText("");
                break;
            case R.id.user_confirm_pwd_show:
                controlEditTextStyle(drawableClose, drawableOpen, mConfirmPassword, mShowConfirmPasswordImage);
                break;
            case R.id.user_confirm_pwd_clear:
                mConfirmPassword.setText("");
                break;
            case R.id.update_password_button:
                updatePassword();
                break;
            case R.id.back_package_list_button:
                showTaskListActivity();
                break;
        }
    }

    @Override
    public void success(Response response) {
        Message logoutSuccessMessage = mHandler.obtainMessage();
        Bundle bundle = new Bundle();
        try {
            String body = response.body().string();
            logoutSuccessMessage.what = Constants.UPDATE_PASSWORD_SUCCESS_MESSAGE;
            bundle.putString("taskBody", body);
            logoutSuccessMessage.setData(bundle);
            Util.debugApp('d', "获取远端信息成功body " + body);
        } catch (IOException e) {
            Util.debugApp('e', "获取远端信息成功但是转换失败" + e.toString());
            logoutSuccessMessage.what = Constants.UPDATE_PASSWORD_FAIL_MESSAGE;
        }
        mHandler.sendMessage(logoutSuccessMessage);
    }

    @Override
    public void fail(IOException exception) {
        Message logoutFailMessage = mHandler.obtainMessage();
        logoutFailMessage.what = Constants.UPDATE_PASSWORD_FAIL_MESSAGE;
        mHandler.sendMessage(logoutFailMessage);
        Util.debugApp('d', "更新密码失败" + exception.toString());
    }

    @Override
    public void codeInvalid(Response response) {
        Message unKnowMessage = mHandler.obtainMessage();
        unKnowMessage.what = Constants.UN_KNOW_RESPONSE_CODE;
        try {
            String body = response.body().string();
            Util.debugApp('d', "codeInvalid " + body);
            Bundle bundle = new Bundle();
            bundle.putString("codeInvalid", body);
            unKnowMessage.setData(bundle);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mHandler.sendMessage(unKnowMessage);
    }
}